<template>
  <div class="home">
    <van-nav-bar
      title="录入信息"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-form validate-first @submit="onSubmit">
      <div block type="info" class="get-area" @click="testNfc">
        刷卡读取身份证信息
      </div>
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        input-align="right"
        label="姓名"
        required
        v-model="formData.name"
        name="pattern"
        placeholder="请输入姓名"
        :rules="[{ required: true, message: '请输入姓名' }]"
      />
      <van-field
        input-align="right"
        label="证件类型"
        required
        v-model="formData.card_type"
        name="pattern"
        placeholder="请选择证件类型"
        @focus="showCertificate = true"
        :rules="[{ required: true, message: '请选择证件类型' }]"
      />
      <van-field
        input-align="right"
        :label="label"
        required
        v-model="formData.card_no"
        @blur="blurCardNo"
        name="pattern"
        placeholder="请输入身份证号"
        :rules="[{ required: true, message: '请输入正确内容' }]"
        maxlength="18"
      />
      <van-field
        input-align="right"
        label="性别"
        required
        v-model="formData.sex"
        name="pattern"
        placeholder="请输入性别"
        :rules="[{ required: true, message: '请输入正确内容' }]"
      />
      <van-field
        input-align="right"
        label="出生日期"
        required
        @focus="showDate = true"
        v-model="formData.bithday"
        name="pattern"
        placeholder="请输入出生日期 例:1975/08/21"
        :rules="[{ required: true, message: '请输入正确内容' }]"
      />
      <van-field
        input-align="right"
        label="户口所在地"
        required
        v-model="formData.household"
        name="pattern"
        placeholder="请输入户口所在地"
        :rules="[{ required: true, message: '请输入正确内容' }]"
      />
      <van-field
        input-align="right"
        label="联系方式"
        v-model="formData.mobile"
        name="phoneRules"
        placeholder="请输入联系方式"
      />
      <div v-show="!isFlag" @click="isFlag = true" class="up-and-down">
        <van-icon name="arrow-down" />
      </div>
      <van-field
        input-align="right"
        label="车次"
        v-show="isFlag"
        v-model="formData.train"
        name="pattern"
        placeholder="请输入车次"
      />
      <van-field
        input-align="right"
        label="车厢"
        v-show="isFlag"
        v-model="formData.carriage"
        name="pattern"
        placeholder="请输入车厢"
      />
      <van-field
        input-align="right"
        label="席位"
        v-show="isFlag"
        v-model="formData.seat"
        name="pattern"
        placeholder="请输入席位"
      />
      <van-field
        input-align="right"
        label="上车站"
        v-show="isFlag"
        v-model="formData.depart"
        name="pattern"
        placeholder="请输入上车站"
      />
      <van-field
        input-align="right"
        label="下车站"
        v-show="isFlag"
        v-model="formData.aim"
        name="pattern"
        placeholder="请输入下车站"
      />
      <van-field
        input-align="right"
        label="上车省市区"
        v-show="isFlag"
        v-model="formData.boarding"
        name="pattern"
        @focus="show = true"
        placeholder="请输入上车省市区"
      />
      <div v-show="isFlag" class="up-and-down" @click="isFlag = false">
        <van-icon name="arrow-up" />
      </div>
      <van-field input-align="right" name="radio" label="途经重点关注地区">
        <template #input>
          <van-radio-group
            v-model="formData.avenue_flow_area"
            direction="horizontal"
          >
            <van-radio name="1">是</van-radio>
            <van-radio name="2">否</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field input-align="right" name="radio" label="48小时核酸证明">
        <template #input>
          <van-radio-group
            v-model="formData.nucleic_acid"
            direction="horizontal"
          >
            <van-radio name="1">是</van-radio>
            <van-radio name="2">否</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        input-align="right"
        label="返连目的地"
        v-model="formData.end_addr"
        name="pattern"
        placeholder="请输入返连目的地"
      />
      <div style="margin: 16px;display:flex;">
        <div block type="info" class="get-area" @click="showControls = true">
          最新管控地区
        </div>
      </div>
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">确认</van-button>
      </div>
    </van-form>
    <!-- 省市区弹出 -->
    <van-popup
      v-model="show"
      closeable
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="title">上车{{ title }}</div>
      <div class="container">
        <div
          class="item"
          v-for="(item, index) in forArea"
          :key="index"
          @click="checkoutArea(item)"
        >
          {{ item.name || item }}
        </div>
      </div>
    </van-popup>
    <!-- 最新管控地区 -->
    <van-dialog v-model="showControls" title="最新管控地区">
      <div class="dialog-container">
        <div
          style="margin: 10px;"
          v-for="(item, index) in controlsList"
          :key="index"
        >
          {{ item.title }}
        </div>
      </div>
    </van-dialog>
    <!-- 证件类型 -->
    <van-popup v-model="showCertificate" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="showCertificate = false"
        @confirm="onConfirm"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="showDate" round position="bottom">
      <van-datetime-picker
        @confirm="getConfirm"
        @cancel="showDate = false"
        :min-date="minDate"
        type="date"
        title="选择年月日"
      />
    </van-popup>
  </div>
</template>

<script>
import area from '@/libs/area.json'
import {
  addPersonnel,
  findMainareaInfoList,
  getFilingInfo
} from '@/api/gov/home'
import { Toast, Dialog } from 'vant'
export default {
  data() {
    return {
      isFlag: false, // 是否显示车次等信息
      minDate: new Date(1900, 0, 1),
      showDate: false, // 选择生日
      label: '身份证号',
      columns: ['身份证', '护照', '军官证', '港澳通行证'],
      formData: {
        card_type: '', // 证件类型
        name: '', // 姓名
        card_no: '', // 身份证
        sex: '', // 性别
        mobile: '',
        bithday: '', // 出生日期
        household: '', // 户口
        train: '', // 车次
        carriage: '', // 车厢
        seat: '', // 席位
        depart: '', // 上车站
        aim: '', // 下车站
        end_addr: '', // 返连目的地
        follow: '2', // 途经重点关注地区
        nuclein: '1', // 持有核酸检测证明
        boarding: '' // 上车省市区
      },
      forArea: area,
      Province: '', // 省
      city: '', // 市
      area: '', // 区
      title: '省', // 标题省  市  区
      show: false, // 城市选择
      pickerShow: false, // 时间选择
      showControls: false, // 最新管控地区弹窗
      controlsList: [],
      isGetArea: false, // 是否已经获取上车省市区
      showCertificate: false, // 证件类型
      phoneRules: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
    }
  },
  mounted() {
    findMainareaInfoList({ type: 1, state: 1 }).then(res => {
      this.controlsList = res.data.data.filter(i => i.state == 1)
    })

    window['getNfcData'] = row => {
      let r = JSON.parse(row)
      console.log(r, 'NFC识别后的参数')
      Toast.clear()
      // if (!r.id) return Toast.fail('nfc读取失败')

      for (let i in this.formData) {
        this.formData[i] = ''
      }
      this.formData.enter_type = this.$route.query.id
      this.formData.nucleic_acid = '1'
      this.formData.avenue_flow_area = '2'

      this.formData.name = r.name || ''
      this.formData.card_no = r.id || ''
      this.formData.sex = r.sex || ''
      r.birthday = r.birthday.replace('年', '/')
      r.birthday = r.birthday.replace('月', '/')
      r.birthday = r.birthday.replace('日', '')
      this.formData.bithday = r.birthday || ''
      this.formData.household = r.address || ''
      this.formData.card_type = '身份证'

      this.blurCardNo()
    }
  },
  methods: {
    getConfirm(value) {
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.bithday = yy + '/' + mm + '/' + dd
      this.showDate = false
    },
    onConfirm(value) {
      this.label = value
      this.formData.card_type = value
      this.showCertificate = false
    },
    blurCardNo() {
      if (this.$route.query.id == 2) {
        getFilingInfo({ card_no: this.formData.card_no }).then(res => {
          if (res.data.errcode != 0) {
            Toast(res.data.errmsg)
            const TIMEOUT = setTimeout(() => {
              clearTimeout(TIMEOUT)
              this.$router.go(-1)
            }, 1500)
          } else {
            for (let i in res.data.data) {
              this.formData[i] = res.data.data[i]
            }
            this.formData.nucleic_acid =
              res.data.data.nuclein == '是' ? '1' : '2'
            this.formData.avenue_flow_area =
              res.data.data.follow == '是' ? '1' : '2'
            this.formData.card_type =
              res.data.data.card_type == 4
                ? '港澳通行证'
                : res.data.data.card_type == 3
                ? '护照'
                : res.data.data.card_type == 2
                ? '军官证'
                : '身份证'
          }
        })
      }
    },
    testNfc() {
      // 测试用户终端
      let u = navigator.userAgent
      let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
      let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

      if (isAndroid) {
        Toast.loading({
          message: '正在识别...',
          forbidClick: true,
          duration: 20000
        })
        window.Android.useNFCReadIdCard('123')
      }
      if (isiOS) {
        return Toast.fail('抱歉\n暂不支持ios')
      }
    },
    onSubmit() {
      let formdata = JSON.parse(JSON.stringify(this.formData))
      formData.nucleic_acid = formData.nucleic_acid == '1' ? '是' : '否'
      formData.avenue_flow_area = formData.avenue_flow_area == '1' ? '是' : '否'
      formdata.personnel_type = this.$route.query.id || 1

      formdata.card_type === '港澳通行证'
        ? (formdata.card_type = 4)
        : formdata.card_type === '军官证'
        ? (formdata.card_type = 2)
        : formdata.card_type === '护照'
        ? (formdata.card_type = 3)
        : (formdata.card_type = 1)
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 10000
      })
      addPersonnel(formdata).then(res => {
        Toast.clear()
        if (res.data.errcode === 0) {
          Dialog.alert({
            message: '提交成功',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
          // 提交成功清空数据
          for (let i in this.formData) {
            this.formData[i] = ''
            this.formData.avenue_flow_area = '2'
            this.formData.nucleic_acid = '1'
          }
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    checkoutArea(item) {
      if (!this.Province) {
        // 选择省
        this.Province = item.name
        this.forArea = item.child
        this.title = '市'
      } else if (!this.city) {
        // 选择市
        this.city = item.name
        this.forArea = item.child
        this.title = '区'
      } else if (!this.area) {
        // 选择区
        this.area = item
        this.show = false
        this.title = '省'
        // 拼接省市区 展示页面
        this.formData.boarding =
          this.Province + '/' + this.city + '/' + this.area

        this.forArea = area
        // 清空省市区 为了下一次选择省市区
        this.Province = ''
        this.city = ''
        this.area = ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
.home {
  img {
    width: 100%;
  }
  .dialog-container {
    height: 70vh;
    overflow-y: auto;
  }
  .get-area {
    width: 100%;
    padding: 0 0.8rem;
    font-size: 0.747rem;
    color: #fff;
    background-color: #1989fa;
    border: 0.053rem solid #1989fa;
    height: 2.347rem;
    line-height: 2.347rem;
    text-align: center;
    border-radius: 0.107rem;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 10px;
  }
  /deep/.van-field__label {
    width: 8em;
  }
  /deep/.van-field__error-message {
    text-align: right;
  }
  .title {
    // font-size: 28px;
    text-indent: 20px;
    padding: 50px 0 20px;
  }
  .container {
    width: 90%;
    height: 80vh;
    overflow-y: auto;
    border: 1px solid #adadad;
    margin: auto;
    .item {
      margin: 10px;
    }
  }
}
.up-and-down {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f1f3f4;
  height: 80px;
  color: #333;
}
</style>
